/**
 Author: 蒋鑫强
 Time: 2023/6/6
 Description: 本地缓存操作indexDB
 */
import localforage from "localforage";
import { type } from '@/util/util';

//配置
localforage.config({
  name: 'tool'
});

export default {
  async setItem(key, value, needClear){
    if (!type.isArray(value)) {
      value = [value];
    }

    if (needClear) {
      return localforage.setItem(key, value);
    } else {
      let result = await this.getItem(key);
      if (result) {
        result = [
          ...result,
          ...value
        ];
      } else {
        result = value;
      }
      return localforage.setItem(key, result);
    }
  },

  getItem(key) {
    return localforage.getItem(key);
  },

  async removeItem(key, list, id = 'id') {
    if (!list) {
      return localforage.removeItem(key);
    } else {
      let result = await this.getItem(key);
      const ids = list.map(d => d[id]);
      result = result.filter(d => !ids.includes(d[id]));
      return this.setItem(key, result, true);
    }
  }
};
